<?php


namespace api\app\controller;


use api\app\model\AddressModel;
use api\app\validate\AddressValidate;
use cmf\controller\RestBaseController;
use think\Request;

class AddressController extends RestBaseController
{
    //查询收货地址列表
    public function list(Request $request)
    {
        $userId = $request->token;
        $address = AddressModel::field('id,name,mobile,ssq,address')
            ->order('id','DESC')
            ->where('user_id',$userId)
            ->select();
        if (!$address){
            $this->error('无收货地址');
        }
        $this->success('查询成功',[
            'address' => $address
        ]);
    }
    //添加收货地址
    public function add(Request $request)
    {
        $userId = $request->token;
        $data = input('post.');
        //验证
        if (!$data){
            $this->error('参数错误');
        }
        $validate = new AddressValidate();
        $res = $validate->scene('add')->check($data);
        if (!$res){
            $this->error($validate->getError());
        }
        $data['user_id'] = $userId;
        $data['create_time'] = time();
        if (AddressModel::create($data)) {
            $this->success('保存成功');
        }else{
            $this->error('保存失败');
        }
    }
    //修改功能
    public function edit()
    {
        $data = input('post.');
        //验证
        if (!$data){
            $this->error('参数错误');
        }
        $validate = new AddressValidate();
        $res = $validate->scene('edit')->check($data);
        if (!$res){
            $this->error($validate->getError());
        }
        $address = AddressModel::find($data['id']);
        if (!$address) {
            $this->error('无此条收货地址');
        }
        $address-> name = $data['name'];
        $address-> mobile = $data['mobile'];
        $address-> ssq = $data['ssq'];
        $address-> address = $data['address'];
        $address-> update_time = time();
        if ($address->save()) {
            $this->success('保存成功');
        }else{
            $this->error('保存失败');
        };

    }
    //删除功能
    public function del()
    {
        $id = input('id/d');
        if (!$id) {
            $this->error('参数错误，id');
        }
        $data = AddressModel::find($id);
        if (!$data) {
            $this->error('未查询到该地址');
        }
        $del = AddressModel::destroy($id);
        if ($del) {
            $this->success('删除成功');
        }else{
            $this->error('删除失败');
        }

    }

}